package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.Backtracking;
import cn.pugle.oj.catalog.Unknown;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/number-of-islands/
 * 洪水算法
 *
 * @author tzp
 * @since 2020/10/20
 */
public class LC200 implements Backtracking {

    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) return 0;

        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    flood(grid, i, j);
                    count++;
                    System.out.println(Arrays.deepToString(grid));
                }
            }
        }
        return count;
    }

    int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    private void flood(char[][] grid, int x, int y) {
        grid[x][y] = 'x';//注意!! 偷个懒, 用x标记已访问过
        for (int k = 0; k < directions.length; k++) {
            int newX = x + directions[k][0];
            int newY = y + directions[k][1];
            if (inArea(grid, newX, newY) && grid[newX][newY] == '1') {
                flood(grid, newX, newY);
            }
        }
    }

    public boolean inArea(char[][] grid, int x, int y) {
        return x >= 0 && y >= 0 && x < grid.length && y < grid[0].length;
    }

    public static void main(String[] args) {
        char[][] a = {
                {'1', '1', '1', '1', '0'},
                {'1', '1', '0', '1', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '0', '0', '0'}};
        System.out.println(new LC200().numIslands(a));
    }
}
